package algorithm.leetcode.I1to100;

import algorithm.leetcode.ListNode;

public class Q2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode fakeHead = new ListNode(-213123);
        ListNode curr = fakeHead;
        // fakeHead.next = curr;
        int prevAdd = 0;

        while (l1 != null || l2 !=null) {
            // 操作本次
            int l1Val = l1 == null ? 0 : l1.val;
            int l2Val = l2 == null ? 0 : l2.val;
            l1Val = l2Val + l1Val + prevAdd;
            prevAdd = l1Val / 10;
            l1Val = l1Val % 10;

            if (l1 != null) {
                curr.next = l1;
                l1.val = l1Val;
                curr = l1;
            } else {
                curr.next = l2;
                l2.val = l1Val;
                curr = l2;
            }
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        if (prevAdd == 1) {
            curr.next = new ListNode(1);
        }

        return fakeHead.next;

    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(4);
        ListNode node3 = new ListNode(9);
        ListNode node4 = new ListNode(5);
        ListNode node5 = new ListNode(6);
        ListNode node6 = new ListNode(4);
        ListNode node7 = new ListNode(9);
        ListNode node8 = new ListNode(6);
        ListNode node9 = new ListNode(7);
        ListNode node10 = new ListNode(5);
        // ListNode node11 = new ListNode(9);
        // ListNode node12 = new ListNode(9);
        node1.next = node2;
        node2.next = node3;
        // node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;
        node7.next = node8;
        node8.next = node9;
        node9.next = node10;
        // node10.next = node11;
        Q2 two = new Q2();
        System.out.println(two.addTwoNumbers(node1, node4));
        // System.out.println(two.addTwoNumbers(node4, node1));


    }
}
